#include <QCoreApplication>
#include <QFile>
#include <QFileInfo>
#include <QList>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QStringList>
#include <QTimer>
#include <QDebug>
#include <QApplication>

#include <assert.h>
#include <stdio.h>

#include "include/DownloadManager.h"

bool DownloadRequest::operator==(const DownloadRequest& r)
{
	return m_url == r.m_url;
}

DownloadManager::DownloadManager(QObject* parent):
	manager(parent)
{
	connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(downloadFinished(QNetworkReply*)));
}

void DownloadManager::doDownload(DownloadRequest drequest)
{
	QNetworkRequest request(drequest.m_url);
	drequest.m_networkReply = manager.get(request);

	currentDownloads.append(drequest);
}

bool DownloadManager::saveToDisk(const QString &filename, QIODevice *data)
{
	QFile file(filename);
	if (!file.open(QIODevice::WriteOnly)) {
		qDebug("Could not open %s for writing: %s\n",
		       qPrintable(filename),
		       qPrintable(file.errorString()));
		return false;
	}

	file.write(data->readAll());
	file.close();

	return true;
}

void DownloadManager::downloadFinished(QNetworkReply *reply)
{
	DownloadRequest request;
	QUrl url = reply->url();
	if (reply->error())
	{
		qDebug("Download of %s failed: %s\n",
		       url.toEncoded().constData(),
		       qPrintable(reply->errorString()));
	} else {

		QString filename = "";
		DownloadRequest request;
		for (int i = 0; i < currentDownloads.size(); i++)
			if (currentDownloads[i].m_networkReply == reply)
			{
				filename = currentDownloads[i].m_filename;
				request = currentDownloads[i];
			}

		int size = reply->size();

		if (saveToDisk(filename, reply))
			qDebug() << "finished, size " << size << " name " << filename << endl;
	}

	currentDownloads.removeAll(request);
	reply->deleteLater();
}
